package com.control;

import com.model.User;
import com.sun.deploy.net.HttpRequest;
import com.sun.deploy.net.HttpResponse;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.ByteBuffer;

@WebServlet("/fileDownload.do")
public class FileDownloadServlet extends HttpServlet {
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String lastUploadName = (String) request.getSession().getAttribute("lastUploadName");
        String filePath = new String();
        if (lastUploadName != null && lastUploadName.indexOf(((User) request.getSession().getAttribute("loginUser")).getUsername()) > -1) {
            filePath = lastUploadName;
        }
        File file = new File(filePath);
        if (!file.exists()) {
            request.setAttribute("errorMessage", "文件不存在");
            request.getRequestDispatcher("menu.jsp").forward(request, response);
            return;
        }
        response.setContentType("application/octet-stream");
        //  System.out.println(URLEncoder.encode((String) request.getSession().getAttribute("fileName"), "utf-8"));
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode((String) request.getSession().getAttribute("fileName"), "utf-8"));
        try (FileInputStream fileInputStream = new FileInputStream(file);
             BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
             OutputStream outputStream = response.getOutputStream();) {
            byte[] buffter = new byte[1024];
            while (bufferedInputStream.read(buffter, 0, 1024) != -1) {
                outputStream.write(buffter);
            }
        }
        request.getRequestDispatcher("menu.jsp").forward(request, response);
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        doPost(request, response);
    }
}
